﻿namespace Resonator.Core.Services
{
	using System;
	using System.ComponentModel.Design;
	using System.IO;
	using Resonator.Domain.Models;
	using Resonator.Domain.Services;

	public class ResourceParserProvider : IResourceParserProvider
	{
		private readonly IServiceProvider _serviceProvider;

		public ResourceParserProvider()
			: this( ResourceParserServiceContainer.Instance )
		{
		}

		public ResourceParserProvider(IServiceProvider serviceProvider)
		{
			if( serviceProvider == null )
			{
				throw new ArgumentNullException( "serviceProvider" );
			}

			_serviceProvider = serviceProvider;
		}

		public virtual IResourceParser Get(ResourceStream stream)
		{
			if( stream == null )
			{
				throw new ArgumentNullException( "stream" );
			}

			string extension = Path.GetExtension( stream.Name ).ToLowerInvariant();

			switch( extension )
			{
				case ".resx":
					return (ResxResourceParser)_serviceProvider.GetService( typeof( ResxResourceParser ) );
				case ".zip":
					return (ZipResourceParser)_serviceProvider.GetService( typeof( ZipResourceParser ) );
				default:
					return null;
			}
		}

		protected class ResourceParserServiceContainer : ServiceContainer
		{
			public static readonly ResourceParserServiceContainer Instance = new ResourceParserServiceContainer();

			public ResourceParserServiceContainer()
			{
				AddService( typeof( ResxResourceParser ), new ResxResourceParser() );
				AddService( typeof( ZipResourceParser ), CreateZipResourceParser );
			}

			public virtual object CreateZipResourceParser(IServiceContainer container, Type serviceType)
			{
				return new ZipResourceParser();
			}
		}
	}
}